%% fdr_correct_pvals.m
%
% [corrected_pvals scaling]=fdr_correct(pvals,threshold)
% Input arguments:  pvals: column vector of pvalues
%                   p-value threshold: default 0.05;
% Output arguments: corrected_pvals: FDR corrected p-values
%                   (corrected=pvals*scaling)
%                   scaling: scaling facotr for FDR correction.
% HL 02.02.12

function [corrected_pvals scaling]=fdr_correct(pvals,threshold)

if nargin<2;
    warning('Threshold not specified. Set to 0.05 by default')
    threshold=0.05;
end
if nargin<1
    error('No p-values provided')
end

[pvals_sorted order]=sort(pvals,1,'descend');

i=1;
while pvals_sorted(i)*length(pvals)/i>threshold
    i=i+1;
    
    if i>length(pvals_sorted)
        error('P-values too big. No FDR correction possible')
    end
    
end
scaling=length(pvals)/i;
corrected_pvals=scaling*pvals;
end